package com.example.stray_animal_management_system.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.stray_animal_management_system.commonu.service.AnimalService;
import com.example.stray_animal_management_system.entity.Animal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/1
 */
@RestController
@RequestMapping("/api/admin/animal")
public class AnimalAdminController {

    @Autowired
    private AnimalService animalService;

    /**
     * 查询所有动物（可分页 + 条件查询）
     */
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(value = "species", required = false) String species,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size
    ) {
        Page<Animal> p = new Page<>(page, size);
        LambdaQueryWrapper<Animal> query = new LambdaQueryWrapper<>();

        if (species != null && !species.isEmpty()) query.eq(Animal::getSpecies, species);
        if (status != null) query.eq(Animal::getStatus, status);
        if (name != null && !name.isEmpty()) query.like(Animal::getName, name);

        IPage<Animal> result = animalService.page(p, query.orderByDesc(Animal::getCreateTime));

        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("data", result.getRecords());
        res.put("total", result.getTotal());
        return res;
    }

    /**
     * 添加动物
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Animal animal) {
        Map<String, Object> res = new HashMap<>();
        animal.setCreateTime(LocalDateTime.now());
        animalService.save(animal);
        res.put("code", 200);
        res.put("msg", "添加成功");
        return res;
    }
    /**
     * 上传动物图片
     */
    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) throws IOException {
        Map<String, Object> res = new HashMap<>();

        if (file.isEmpty()) {
            res.put("code", 400);
            res.put("msg", "文件为空");
            return res;
        }

        // 上传目录（例如 /uploads/animals/）
        String uploadDir = System.getProperty("user.dir") + "/uploads/animals/";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成文件名（保证唯一）
        String suffix = file.getOriginalFilename()
                .substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = "animal_" + System.currentTimeMillis() + suffix;

        // 保存文件到本地
        File dest = new File(uploadDir + fileName);
        file.transferTo(dest);

        // 图片访问路径（你需要在 WebConfig 里映射静态目录）
        String url = "http://localhost:8080/uploads/animals/" + fileName;

        res.put("code", 200);
        res.put("msg", "上传成功");
        res.put("url", url);
        return res;
    }

    /**
     * 更新动物信息
     */
    @PutMapping("/update")
    public Map<String, Object> update(@RequestBody Animal animal) {
        Map<String, Object> res = new HashMap<>();
        animalService.updateById(animal);
        res.put("code", 200);
        res.put("msg", "更新成功");
        return res;
    }

    /**
     * 删除动物（支持批量）
     */
    @DeleteMapping("/delete")
    public Map<String, Object> delete(@RequestParam("ids") List<Integer> ids) {
        Map<String, Object> res = new HashMap<>();
        animalService.removeByIds(ids);
        res.put("code", 200);
        res.put("msg", "删除成功");
        return res;
    }
}
